<template>
  <view>
    <web-view :src="src" @message="handleViewMessage"></web-view>
  </view>
</template>
<script setup>
import { onShareAppMessage, onLoad } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
import { ObjectToQueryString, ossImg } from "@/utils/utils";
import { onMounted } from "vue";
import { config, ShareConfig } from "./config";

const src = ref("");
const sceneObj = reactive({ scene: "", wx_scene: 0, q: '' })
const locationInfo = reactive({ latitude: "", longitude: "" })
const shareScene = ref('')

const getQueryParams = (user = {}, exactParams = {}) => ({
  'accesstoken': uni.getStorageSync("TOKEN"),
  'openid': uni.getStorageSync("OPENID"),
  'unionid': uni.getStorageSync("UNIONID"),
  'memberid': user?.memberScore?.memberId || '',
  'agree': 'true',
  latitude: locationInfo.latitude,
  longitude: locationInfo.longitude,
  ...exactParams
})

onLoad(options => {
  getApp().accessLogAdd();
  sceneObj.scene = options?.scene || ""
  sceneObj.wx_scene = uni.getLaunchOptionsSync().scene
  sceneObj.q = options.q || ''
})

onMounted(async () => {
  uni.getLocation({
    type: "gcj02",
    success: (result) => {
      Object.assign(locationInfo, result)
    },
    async complete() {
      if (!getQueryParams().openid) {
        try {
          await getApp().getUserLoginInfo()
          const user = await getApp().getUserInfo()
          const params = getQueryParams(user, sceneObj)
          src.value = `${config.hostname}?${ObjectToQueryString(params)}`
        } catch (e) {
          uni.showToast({ title: '服务器响应错误', icon: 'none' })
        }
        return
      }
      src.value = `${config.hostname}?${ObjectToQueryString(getQueryParams({}, sceneObj))}`
    },
  })
})

const handleViewMessage = ({ detail }) => {
  const { scene } = detail.data?.at(-1)
  if (scene) shareScene.value = scene
}


onShareAppMessage(() => {
  if (!src.value.includes('shareSuc=1')) src.value += '#shareSuc=1'
  return {
    title: '即刻点击，玩转玩心，参与更多抽奖活动~',
    imageUrl: ossImg('others/biscuithouse/share_cover.jpg'),
    path: `/campaign/pages/biscuithouse/index?scene=${shareScene.value}`
  }
})
</script>

<style></style>
